using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Minions.Classes;
using jQueryApi;

namespace MinionsEdit.Classes
{
    [IgnoreNamespace]
    public class MiPopChoice : TinyPopup
    {
        private readonly Dictionary<string, jQueryEventHandler> _choices;
        private readonly jQueryEvent _e;
        private readonly jQueryObject _ul;
        private jQueryEventHandler _cancelEv;

        private const string BasicCss = @"
        .MiPopChoice {
            width: 500px;
        }
        .MiPopChoice ul {
            list-style-type: none;
            padding: 0;
            margin: 5px 10px;
        }
        .MiPopChoice a {
            color: black;
        }
        .MiPopChoice a:active {
            color: black;
        }
        .MiPopChoice a:visited {
            color: black;
        }
        .MiPopChoice a:hover {
            color: #666;
            cursor: default;
        }
        ";

        static MiPopChoice()
        {
            AddStyle(BasicCss);
        }

        public MiPopChoice(jQueryEvent e, Pos pos, Dictionary<string, jQueryEventHandler> choices)
        {
            _e = e;
            _choices = choices;

            Element.AddClass("MiPopChoice");

            _ul = jQuery.FromHtml("<ul/>")
                .AppendTo(Element)
                ;

            Element.CSS(
                new Dictionary(
                    "top", pos.Top,
                    "left", pos.Left
                    ));

            foreach (KeyValuePair<string, jQueryEventHandler> pair in _choices)
            {
                BuildClosure(pair.Key, pair.Value);
            }
        }

        public MiPopChoice Css(Dictionary css)
        {
            Element.CSS(css);
            return this;
        }

        public MiPopChoice SetCancel(jQueryEventHandler fn)
        {
            _cancelEv = fn;
            return this;
        }

        protected override void CancelEv(jQueryEvent e)
        {
            if (_cancelEv != null)
                _cancelEv(e);
            base.CancelEv(e);
        }

        private void BuildClosure(string key, jQueryEventHandler fn)
        {
            jQuery.FromHtml("<li/>")
                .AppendTo(_ul)
                .Append(
                    jQuery.FromHtml("<input type='radio'/>")
                        .Click(delegate(jQueryEvent e)
                               {
                                   Destroy(e);
                                   fn(e);
                               })
                )
                .Append(
                    jQuery.FromHtml("<a/>")
                        .Html(key)
                        .Click(delegate(jQueryEvent e)
                        {
                            Destroy(e);
                            fn(e);
                        })
                )
                ;
        }
    }
}